/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.eric.nioclient.service;


import com.eric.nioclient.service.packet.ChatToGroupPacket;
import com.eric.nioclient.service.packet.NoticePacket;
import com.eric.nioclient.service.packet.Packet;
import com.eric.nioclient.service.packet.UserOutPacket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


public class ServiceHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext client ;
    Logic logic = Logic.me();

    public ServiceHandler() {

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        logic.setChannel(ctx.channel());
        logic.fireConnectActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        Packet packet = (Packet)msg;
        String result = null;
        switch (packet.getPacketType()){
            case NoticeClient:
                NoticePacket noticePacket = (NoticePacket)packet;
                if("login_ok".equals(noticePacket.msg)){
                    logic.fireLoginStatus(true);
                    return;
                }else if("login_fail".equals(noticePacket.msg)){
                    logic.fireLoginStatus(false);
                    return;
                }
                logic.fireServiceNotice(noticePacket.msg);
                break;
            case UserOut:
                UserOutPacket userOutPacket = (UserOutPacket)packet;
                result = "强制退出: "+userOutPacket.reason;
                break;
            case ChatToGroup:
                ChatToGroupPacket chatToGroupPacket = (ChatToGroupPacket)packet;
                logic.fireReceivedMsg(chatToGroupPacket.user,chatToGroupPacket.msg);
                break;
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
//       ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
